package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"rbacmgr/cache"
	"rbacmgr/moderls"
	"rbacmgr/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	var user moderls.User

	redis_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	err := moderls.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {

		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2个小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return
}

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))

	offset := (page - 1) * size

	var count int64

	moderls.DB.Model(&moderls.Rbac{}).Count(&count)

	var rbac []moderls.Rbac

	redis_key := "list"

	checkData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if checkData == "" {
		moderls.DB.Offset(offset).Limit(size).Find(&rbac)
		jsonData, _ := json.Marshal(rbac)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(checkData), &rbac)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  rbac,
		"count": count,
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var rbac moderls.Rbac

	redis_key := "detail" + id

	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		moderls.DB.Where("id=?", id).First(&rbac)
		jsonData, _ := json.Marshal(rbac)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &rbac)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": rbac,
	})
	return
}
